package com.dcbeida.activity.login;


import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.InputFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.dcbeida.MyApplication;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.HomeActivity;
import com.dcbeida.utils.PasswordFilter;
import com.dcbeida.utils.SharedPreferencesUtils;
import com.dcbeida.utils.permission.AndPermission;
import com.dcbeida.utils.permission.PermissionListener;
import com.dcbeida.utils.permission.Rationale;
import com.dcbeida.utils.permission.RationaleListener;
import com.dcbeida.widget.TipDialog;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;


public class LoginWithCodeActivity extends BaseActivity implements View.OnClickListener, LoginContract.View {


    @Bind(R.id.input_email)
    EditText _emailText;
    @Bind(R.id.tv_get_code)
    TextView tvGetCode;
    @Bind(R.id.tv_count_down)
    TextView tvCountDown;

    @Bind(R.id.input_password)
    EditText _passwordText;
    @Bind(R.id.btn_login)
    TextView _loginButton;
    @Bind(R.id.tv_change)
    TextView tv_change;
    private LoginContract.Present mPresent;

    SharedPreferencesUtils sp;
    private CountDownTimer mCountDownTimer;
    private String tel;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login3;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        sp = SharedPreferencesUtils.getInstance(LoginWithCodeActivity.this);
        MyApplication.user = null;
        sp.setUser(null);
        tel = sp.getPhone();
        _loginButton.setOnClickListener(this);
        tv_change.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        initParams();
        initCount();
        Activity activity = MyApplication.getInstance().findActivity(HomeActivity.class);
        if (activity != null)
            activity.finish();

    }

    private void initParams() {
        _emailText.setText(tel);
        mPresent = new LoginPresenter(this, this);
    }


    @Override
    public void loginError(String msg, int type) {

        if (type == mPresent.ACCOUNTNOERROR)
            _emailText.setError(msg);
        else if (type == mPresent.ACCOUNTNOERROR) {
            _passwordText.setError(msg);
        }
    }

    @Override
    public void loginSuccess() {
        mCountDownTimer.onFinish();
        sp.setUser(MyApplication.user);
        sp.setPhone(_emailText.getText().toString());
        showActivity(HomeActivity.class, null);
        this.finish();
    }

    @Override
    public void sendCodeStatus(int status) {
        if (status == 1) {
            showTip("验证码已发送");
            tvGetCode.setVisibility(View.GONE);
            tvCountDown.setText("");
            tvCountDown.setVisibility(View.VISIBLE);
            countDown();
        } else {
            showTip("验证码发送失败");
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCountDownTimer.cancel();
    }

    private void initCount() {
        mCountDownTimer = new CountDownTimer(60 * 1000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                Log.i("fancl", "----->" + millisUntilFinished);
                tvCountDown.setText((millisUntilFinished / 1000) + "s");
            }

            @Override
            public void onFinish() {
                Log.i("fancl", "----->finish");
                tvCountDown.setVisibility(View.GONE);
                tvCountDown.setText("");
                tvGetCode.setVisibility(View.VISIBLE);

            }
        };
    }

    private void countDown() {
        mCountDownTimer.start();

    }


    @Override
    public String getAccount() {
        return _emailText.getText().toString();
    }

    @Override
    public String getPassword() {
        return _passwordText.getText().toString();

    }

    @Override
    public void showTip(String msg) {
        super.showTip(msg);
    }

    @Override
    public void dissP() {

    }

    @Override
    public void showP() {

    }

    @Override
    public void showError(String message) {
        TipDialog tipDialog = new TipDialog(mContext).setMessage(message);
        tipDialog.show();
    }


    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "17300935806"));

    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            rationale.resume();
        }
    };

    @Override
    public void setPresenter(LoginContract.Present presenter) {

    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantPermissions) {
            startActivity(intent);
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            if (AndPermission.hasAlwaysDeniedPermission(LoginWithCodeActivity.this, deniedPermissions)) {

                Toast.makeText(LoginWithCodeActivity.this, R.string.permissionstr, Toast.LENGTH_SHORT).show();
            } else {

                Toast.makeText(LoginWithCodeActivity.this, R.string.qxhqsb, Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                mPresent.login(0);
                break;
            case R.id.tv_get_code:
                   break;
            case R.id.tv_change:
//                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
//                    AndPermission.with(LoginWithCodeActivity.this)
//                            .requestCode(100)
//                            .permission(Manifest.permission.CALL_PHONE)
//                            .rationale(rationaleListener)
//                            .send();
//                    return;
//                } else {
//                    startActivity(intent);
//                }
                showActivity(LoginActivity.class, null);
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            android.os.Process.killProcess(android.os.Process.myPid());
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}

